#include "ZenFace.h"

CZenFace::CZenFace()
{
	m_pTexture		= 0;
	m_bTextureSet	= FALSE;
}

CZenFace::~CZenFace()
{
	if (m_pTexture)
		m_pTexture->Release();
}

void CZenFace::SetProps(int Vertex, float  x, float  y, float  z, float nx, float ny, float nz,
						D3DCOLOR DiffuseColor, D3DCOLOR SpecularColor, float tu, float tv)
{
	m_Vertices[Vertex].m_Position.x = x;
	m_Vertices[Vertex].m_Position.y = y;
	m_Vertices[Vertex].m_Position.z = z;

	m_Vertices[Vertex].m_Normal.x = nx;
	m_Vertices[Vertex].m_Normal.y = ny;
	m_Vertices[Vertex].m_Normal.z = nz;

	m_Vertices[Vertex].m_DiffuseColor  = DiffuseColor;
	m_Vertices[Vertex].m_SpecularColor = SpecularColor;

	m_Vertices[Vertex].m_tu = tu;
	m_Vertices[Vertex].m_tv = tv;
}

HRESULT CZenFace::SetTexture(LPDIRECT3DTEXTURE8 pTexture)
{
	if (!pTexture)
	{
		m_bTextureSet = FALSE;
		return E_FAIL;
	}

	if (m_pTexture)
		m_pTexture->Release();

	m_pTexture = pTexture;
	m_pTexture->AddRef();

	m_bTextureSet = TRUE;

	return S_OK;
}

HRESULT CZenFace::SetTexture(char * strPathName)
{
		HRESULT res = 0;

	if (m_pTexture)
		m_pTexture->Release();

	res = D3DXCreateTextureFromFile(zen.m_pDevice, strPathName, &m_pTexture);
	if (SUCCEEDED(res))
	{
		m_bTextureSet = TRUE;
		return S_OK;
	}

	return E_FAIL;
}

HRESULT CZenFace::Render()
{
	HRESULT					res   = 0;
	LPDIRECT3DVERTEXBUFFER8	pVB   = 0;
	BYTE *					pData = 0;
	
	res = zen.m_pDevice->CreateVertexBuffer(sizeof(CZenVertex) * 3, D3DUSAGE_WRITEONLY,
											ZENVERTEX_TYPE, D3DPOOL_DEFAULT, &pVB);
	if (FAILED(res))
		return E_FAIL;

	res = pVB->Lock(0, 0, &pData, 0);
	if (FAILED(res))
	{
		pVB->Release();
		return E_FAIL;
	}
	
	CopyMemory(pData, (void*)&m_Vertices, sizeof(CZenVertex) * 3);

	pVB->Unlock();

	if (m_pTexture)
		zen.m_pDevice->SetTexture(0, m_pTexture);

	zen.m_pDevice->SetStreamSource(0, pVB, sizeof(CZenVertex));
	zen.m_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

	if (m_pTexture)
		zen.m_pDevice->SetTexture(0, NULL);

	pVB->Release();

	return S_OK;
}
